package com.lagou.test04.test03;

import java.io.*;

public class FileCopyRunnable implements Runnable {

    private File sourceFile;
    private String targetPath;

    public FileCopyRunnable(File sourceFile, String targetPath) {
        this.sourceFile = sourceFile;
        this.targetPath = targetPath;
    }

    @Override
    public void run() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            //创建文件输入流
            bis = new BufferedInputStream(new FileInputStream(sourceFile));
            //创建输出流
            bos = new BufferedOutputStream(new FileOutputStream(targetPath));
            //创建缓冲区
            byte[] bArr = new byte[1024];
            int res = 0;
            //读取文件并写入
            while((res=bis.read(bArr))!=-1){
                bos.write(bArr,0,res);
            }

            System.out.println("线程"+Thread.currentThread().getName()+"--"+sourceFile.getName()+"拷贝成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
